package com.k.kpp.web.easyexcel2.handler;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;

import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * handler
 *
 * @author ljw
 */
public class I18nCellWriteHandler implements CellWriteHandler {
    private final static char[] PLACEHOLDERS = {'{', '}'};
    private Locale locale;

    public I18nCellWriteHandler() {
    }

    public I18nCellWriteHandler(Locale locale) {
        this.locale = locale;
    }

    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
        if (isHead) {
            List<String> originHeadNames = head.getHeadNameList();
            if (CollectionUtils.isNotEmpty(originHeadNames)) {
                List<String> newHeadNames = originHeadNames.stream().
                        map(this::resolveHeadName
                        ).collect(Collectors.toList());
                System.out.println(newHeadNames);
                head.setHeadNameList(newHeadNames);
            }
        }
    }

    private String resolveHeadName(String headName) {
        if (StringUtils.isNotBlank(headName)) {
            char[] c = headName.toCharArray();
            if (PLACEHOLDERS[0] == c[0] && PLACEHOLDERS[1] == c[headName.length() - 1]) {
                String key = headName.substring(1, headName.length() - 1);
                return getI18N(key, locale);
            }
        }
        return headName;
    }

    private String getI18N(String key, Locale locale) {
        return key + "_" + locale.toLanguageTag();
    }
}